from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.openapi.docs import get_swagger_ui_html, get_redoc_html
from fastapi.openapi.utils import get_openapi
from fastapi.responses import JSONResponse, HTMLResponse
from starlette.middleware import Middleware
from sqlalchemy import text
from app.api.v1.api import api_router
from app.core.config import settings
from app.db.init_db import init
from app.db.session import SessionLocal

# 配置CORS中间件
origins = ["*"]  # 在生产环境中需要设置具体的源
middleware = [
    Middleware(
        CORSMiddleware,
        allow_origins=origins,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
]

app = FastAPI(
    title="EduCool API",
    version="1.0.0",
    middleware=middleware,
    description="A platform for guiding children's learning and education",
    # 禁用默认的docs和openapi端点，我们将手动添加它们
    openapi_url=None,
    docs_url=None,
    redoc_url=None
)

@app.get("/openapi.json")
async def get_open_api_endpoint():
    return JSONResponse(get_openapi(
        title="EduCool API",
        version="1.0.0",
        description="A platform for guiding children's learning and education",
        routes=app.routes
    ))

@app.get("/docs", response_class=HTMLResponse)
async def get_swagger_documentation(request: Request):
    return get_swagger_ui_html(
        openapi_url="/openapi.json",
        title="EduCool API - Swagger UI",
        swagger_js_url="https://unpkg.com/swagger-ui-dist@5.9.0/swagger-ui-bundle.js",
        swagger_css_url="https://unpkg.com/swagger-ui-dist@5.9.0/swagger-ui.css",
        swagger_favicon_url="https://fastapi.tiangolo.com/img/favicon.png"
    )

@app.get("/redoc", response_class=HTMLResponse)
async def get_redoc_documentation(request: Request):
    return get_redoc_html(
        openapi_url="/openapi.json",
        title="EduCool API - ReDoc",
        redoc_js_url="https://unpkg.com/redoc@latest/bundles/redoc.standalone.js",
        redoc_favicon_url="https://fastapi.tiangolo.com/img/favicon.png"
    )

# 不再需要手动添加中间件，因为已经在FastAPI初始化时配置
# 包含API路由
app.include_router(api_router, prefix=settings.API_V1_STR)

# 挂载静态文件
app.mount("/admin", StaticFiles(directory="../frontend/admin/dist", html=True), name="admin")

@app.on_event("startup")
async def startup_event():
    """应用启动时初始化数据库"""
    init()

@app.get("/")
async def root():
    return {"message": "Welcome to EduCool Learning Platform API"}

@app.get("/health")
async def health_check():
    return {"status": "healthy"}

def test_db_connection():
    """测试数据库连接是否正常"""
    try:
        db = SessionLocal()
        # 执行一个简单的SQL查询来测试连接
        result = db.execute(text("SELECT 1"))
        db.close()
        return True
    except Exception as e:
        import logging
        logging.error(f"数据库连接测试失败: {str(e)}")
        return False

@app.get("/db-health")
async def db_health_check():
    """检查数据库连接健康状态"""
    is_connected = test_db_connection()
    if is_connected:
        return {"status": "database connection healthy"}
    else:
        return JSONResponse(
            content={"status": "database connection failed"},
            status_code=500
        )